<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="番剧名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入内容"/>
      </el-form-item>
      <el-form-item label="头图" prop="headImg">
        <el-input v-model="queryParams.headImg" placeholder="请输入内容"/>
      </el-form-item>
      <el-form-item label="简介" prop="profiles">
        <el-input v-model="queryParams.profiles" placeholder="请输入内容"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary"
                   plain
                   icon="el-icon-plus"
                   size="mini"
                   @click="handleAdd"
                   v-hasPermi="['video:video:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success"
                   plain
                   icon="el-icon-edit"
                   size="mini"
                   :disabled="single"
                   @click="handleUpdate"
                   v-hasPermi="['video:video:edit']">修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger"
                   plain
                   icon="el-icon-delete"
                   size="mini"
                   :disabled="multiple"
                   @click="handleDelete"
                   v-hasPermi="['video:video:remove']">删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning"
                   plain
                   icon="el-icon-download"
                   size="mini"
                   @click="handleExport"
                   v-hasPermi="['video:video:export']">导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button plain
                   icon="el-icon-refresh"
                   size="mini"
                   @click="syncVideoFolder"
                   v-hasPermi="['video:video:export']">扫描视频路径
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" align="center" prop="id"/>
      <el-table-column label="番剧名称" align="center" prop="name"/>
      <el-table-column label="设置观看进度" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-radio-group v-model="scope.row.progress" size="mini" @change="setVideoProgress(scope.row)">
            <el-radio-button label="0">未看</el-radio-button>
            <el-radio-button label="1">在看</el-radio-button>
            <el-radio-button label="2">已看完</el-radio-button>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column label="头图" align="center" prop="headImg"/>
      <el-table-column label="简介" align="center" prop="profiles"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini"
                     type="text"
                     icon="el-icon-edit"
                     @click="handleUpdate(scope.row)"
                     v-hasPermi="['video:video:edit']">修改
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-delete"
                     @click="handleDelete(scope.row)"
                     v-hasPermi="['video:video:remove']">删除
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-video-play"
                     @click="playVideo(scope.row)"
                     v-hasPermi="['video:video:remove']">播放
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-upload"
                     @click="showUploadVideoFileDialog(scope.row)"
                     v-hasPermi="['video:video:upload']">上传视频
          </el-button>
          <el-button size="mini"
                     type="text"
                     icon="el-icon-link"
                     @click="showLinkVideoDialog(scope.row)"
                     v-hasPermi="['video:video:edit']">关联其他番剧
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"/>
    <!-- 添加或修改番剧对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="番剧名称" prop="name">
          <el-input v-model="form.name" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="头图" prop="headImg" v-show="false">
          <el-input v-model="form.headImg" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item>
          <el-upload
            class="avatar-uploader"
            action=""
            :show-file-list="false"
            :http-request="uploadHeadImg_"
            :before-upload="beforeAvatarUpload">
            <img v-if="form.headImg" :src="getHeadImg(form.headImg)" class="avatar"/>
            <el-icon v-else class="avatar-uploader-icon">
              <plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="profiles">
          <el-input v-model="form.profiles" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="上传视频" :visible.sync="uploadVideoFileDialog" @close="clearUploadVideoFileDialogData">
      <el-upload action=""
                 ref="upload"
                 :http-request="uploadvideo_"
                 :show-file-list="false"
                 :multiple="true"
                 :before-upload="videoHandlePreview"
                 :auto-upload="true">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传并保存</el-button>
        <div slot="tip" class="el-upload__tip">仅支持mp4,mkv,flv,mov</div>
      </el-upload>
      <!--使用draggable组件-->
      <draggable v-model="fileList" chosenClass="chosen" forceFallback="true" group="people" animation="1000"
                 @end="onEnd">
        <transition-group>
          <div class="item" v-for="(f,i) in fileList" :key="f.fileName">{{ f.fileName }}</div>
        </transition-group>
      </draggable>
    </el-dialog>
    <el-dialog title="关联其他番剧" :visible.sync="linkVideoDialogData.nowShowLinkVideoDialog" width="800px"
               @close="clearLinkVideoDialogData">
      <el-input
        placeholder="输入番剧名称,回车搜索"
        v-model="linkVideoDialogData.linkVideoDialoginput"
        @change="getOrtherVideo()"
        clearable>
      </el-input>
      <div style="margin-top: 20px;">
        <el-table
          ref="multipleTable"
          :data="linkVideoDialogData.ortherVideoList"
          tooltip-effect="dark"
          style="width: 100%;"
          @row-click="addSelectToLinkList">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="番剧名称">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 20px;">
        <el-table
          ref="multipleTable"
          :data="linkVideoDialogData.linkedVideos"
          @row-click="deleteSelectToLinkList"
          tooltip-effect="dark"
          style="width: 100%;">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="待关联番剧">
            <template slot-scope="scope">{{ scope.row.name }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div style="margin-top: 20px;">
        <el-button plain @click="clearLinkVideoDialogData" style="margin-right: 20px;">关闭</el-button>
        <el-button type="primary" @click="linkOrtherVideo" plain>关联</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addVideo,
  batchSaveVideoFile,
  delVideo,
  getVideo,
  listVideo,
  syncVideoFolder,
  updateVideo,
  uploadHeadImg,
  uploadVideo
} from '@/api/video/video'
import { listVideoFile } from '@/api/video/videoFile'
import { Message } from 'element-ui'
import draggable from 'vuedraggable'
import { addRelation, getRelationVideos } from '@/api/video/relation'
import { addProgress } from '@/api/video/progress'

export default {
  name: 'Video',
  components: {
    draggable
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 番剧表格数据
      videoList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        headImg: null,
        profiles: null,
        orderByColumn: 'createTime',
        isAsc: 'desc'
      },
      // 表单参数
      form: {
        name: '',
        headImg: ''
      },
      // 表单校验
      rules: {},
      //===========================视频文件上传
      uploadVideoFileDialog: false,
      fileList: [],
      nowShowDialog: {},
      //番剧关联
      linkVideoDialogData: {
        nowShowLinkVideoDialog: false,
        linkVideoDialog: null,
        linkVideoDialoginput: '',
        linkedVideos: [],
        ortherVideoList: []
      },
      videoProgress: '未看'
    }
  },
  created() {
    this.getList()
  },
  mounted() {
  },
  methods: {
    getHeadImg(src) {
      return src ? (process.env.VUE_APP_BASE_API + src) : ''
    },
    syncVideoFolder() {
      syncVideoFolder().then(res => {
        if (res.code === 200) {
          Message.success('刷新完毕')
        } else {
          Message.error(res.msg)
        }
      })
    },
    setVideoProgress(video) {
      addProgress({ videoId: video.id, progress: video.progress }).then(res => {
        if (res.code === 200) {
          Message.success('设置观看进度成功')
        } else {
          Message.error(res.msg)
        }
      })
    },
    /**
     * 播放视频
     * @param video
     */
    playVideo(video) {
      window.open('/videoPlayer/' + video.id)
    },
    //清除关联番剧的弹窗数据同时关闭弹窗
    clearLinkVideoDialogData() {
      this.linkVideoDialogData = {
        nowShowLinkVideoDialog: false,
        linkVideoDialog: null,
        linkVideoDialoginput: '',
        linkedVideos: [],
        ortherVideoList: []
      }
    },
    //将选中的视频添加到选中区
    addSelectToLinkList(row, col, eve) {
      if (this.linkVideoDialogData.linkedVideos.indexOf(row) === -1) {
        this.linkVideoDialogData.linkedVideos.push(row)
      }
      this.linkVideoDialogData.ortherVideoList.splice(this.linkVideoDialogData.ortherVideoList.indexOf(row), 1)
    },
    deleteSelectToLinkList(row, col, eve) {
      this.linkVideoDialogData.linkedVideos.splice(this.linkVideoDialogData.linkedVideos.indexOf(row), 1)
    },
    /**
     * 展示弹窗
     * @param video
     */
    showLinkVideoDialog(video) {
      this.linkVideoDialogData.nowShowLinkVideoDialog = true
      this.linkVideoDialogData.linkVideoDialog = video
      getRelationVideos(video.id).then(res => {
        if (res.code === 200) {
          if (res.data) {
            this.linkVideoDialogData.linkedVideos = res.data
            //清除当前视频
            for (let i = 0; i < this.linkVideoDialogData.linkedVideos.length; i++) {
              if (this.linkVideoDialogData.linkedVideos[i].id === video.id) {
                this.linkVideoDialogData.linkedVideos.splice(i, 1)
                break
              }
            }
          }
        }
      })
    },
    /**
     * 搜索番剧
     */
    getOrtherVideo() {
      if (this.linkVideoDialogData.linkVideoDialoginput) {
        listVideo({ name: this.linkVideoDialogData.linkVideoDialoginput }).then(res => {
          this.linkVideoDialogData.ortherVideoList = res.rows
          //删除当前元素
          for (let i = 0; i < this.linkVideoDialogData.ortherVideoList.length; i++) {
            if (this.linkVideoDialogData.ortherVideoList[i].id === this.linkVideoDialogData.linkVideoDialog.id) {
              this.linkVideoDialogData.ortherVideoList.splice(i, 1)
              break
            }
          }
        })
      }
    },
    /**
     * 链接其他video
     */
    linkOrtherVideo() {
      let videoIds = this.linkVideoDialogData.linkVideoDialog.id + ','
      this.linkVideoDialogData.linkedVideos.map(item => {
        videoIds += item.id + ','
      })
      addRelation({ videoIds }).then(res => {
        if (res.code === 200) {
          Message.success('关联成功')
          //清空数据,关闭弹窗
          this.clearLinkVideoDialogData()
        } else {
          Message.error('关联失败')
        }
      })
    },
    /**
     * 上传视频弹窗关闭时清空数据
     */
    clearUploadVideoFileDialogData() {
      this.fileList = []
      this.nowShowDialog = {}
    },
    //拖拽结束事件
    onEnd() {
      //console.log(this.fileList)
    },
    /**
     * 提交文件列表
     */
    submitUpload() {
      batchSaveVideoFile(this.fileList).then(res => {
        if (res.code === 200) {
          Message.success('保存成功')
          this.uploadVideoFileDialog = false
          this.nowShowDialog = {}
          this.fileList = []
        }
      })
    },
    /**
     * 展示上传视频弹窗
     * @param row
     */
    showUploadVideoFileDialog(row) {
      this.uploadVideoFileDialog = true
      this.nowShowDialog = row
      listVideoFile({ videoId: row.id }).then(res => {
        res.rows.map(i => {
          this.fileList.push(i)
        })
      })
    },
    /**
     * 视频上传校验
     * @param file
     * @returns {boolean}
     */
    videoHandlePreview(file) {
      const fileType = file.type === 'video/mp4' || file.type === 'video/x-matroska' || file.type === 'video/quicktime' || (file.type === '' && file.name.length > 4 ? (file.name.slice(-3) === 'flv') : false)
      if (!fileType) {
        Message.error('文件格式仅支持mp4,mkv,flv,mov')
      }
      return fileType
    },
    /**
     * 视频上传方法
     * @param params
     * @private
     */
    uploadvideo_(params) {
      let formData = new FormData()
      formData.append('video', params.file)//
      uploadVideo(formData).then(res => {
        if (res.code === 200) {
          Message.success('上传成功')
          let fileName = params.file.name
          let mime = this.getMime(params.file)
          this.fileList.push({
            fileName,
            filePath: res.msg,
            extendedName: mime,
            videoId: this.nowShowDialog.id
          })
          params.onSuccess(params)
        } else if (res.code === 500) {
          Message.error(res.msg)
          params.onError(params)
        }
      })
    },
    getMime(file) {
      if (file.type === '' && file.name.length > 4 && file.name.slice(-3) === 'flv') {
        return 'flv-application/octet-stream'
      } else {
        return file.type
      }
    },
    /**
     * 头图上传方法
     * @param params
     * @private
     */
    uploadHeadImg_(params) {
      let formData = new FormData()
      formData.append('avatarfile', params.file)
      uploadHeadImg(formData).then(res => {
        this.form.headImg = res.msg
      })
    },
    /**
     * 头图上传校验
     * @param file
     * @returns {boolean}
     */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        Message.error('文件格式仅支持jpg,png,gif')
      }
      if (!isLt2M) {
        Message.error('图片大于10M!')
      }
      return isJPG && isLt2M
    },
    /** 查询番剧列表 */
    getList() {
      this.loading = true
      listVideo(this.queryParams).then(response => {
        this.videoList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        headImg: null,
        profiles: null,
        createTime: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加番剧'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getVideo(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = '修改番剧'
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVideo(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addVideo(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除番剧编号为"' + ids + '"的数据项？').then(function() {
        return delVideo(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('video/video/export', {
        ...this.queryParams
      }, `video_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  min-height: 50px;
  min-width: 50px;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 192px;
  /*height: 108px;*/
  display: block;
}

/*被拖拽对象的样式*/
.item {
  padding: 6px;
  background-color: #fdfdfd;
  border: solid 1px #eee;
  margin-bottom: 10px;
  cursor: move;
}

/*选中样式*/
.chosen {
  border: solid 2px #3089dc !important;
}
</style>
